// Imports
import Vue from 'vue'
import Router from 'vue-router'
import { trailingSlash } from '@/util/helpers'
import {
  layout,
  route,
} from '@/util/routes'
import cookies from '@/util/cookies'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  scrollBehavior: (to, from, savedPosition) => {
    if (to.hash) return { selector: to.hash }
    if (savedPosition) return savedPosition

    return { x: 0, y: 0 }
  },
  routes: [
    layout('Default', [
      // Pages
      // Home
      route('Home'),
      route('Status', null, { auth: true }, 'apptpl/status'),
      route('Config', null, { auth: true }, 'apptpl/config'),

      // 登录
      // route('Login', null, { auth: true }, 'login'),
    ]),
    {
      name: 'Login',
      path: '/login',
      component: () => import('@/views/Login.vue'),
    },
  ],
})

// router.beforeEach((to, from, next) => {
//   return to.path.endsWith('/') ? next() : next(trailingSlash(to.path))
// })

router.beforeEach((to, from, next) => {
  // 验证当前路由所有的匹配中是否需要有登录验证的
  if (to.matched.some(r => r.meta.auth)) {
    // 这里暂时将cookie里是否存有token作为验证是否登录的条件
    // 请根据自身业务需要修改
    const token = cookies.get('token')
    if (token && token !== 'undefined') {
      return to.path.endsWith('/') ? next() : next(trailingSlash(to.path))
    } else {
      // 没有登录的时候跳转到登录界面
      // 携带上登陆成功之后需要跳转的页面完整路径
      next({
        name: 'Login',
        query: {
          redirect: to.fullPath,
        },
      })
    }
  } else {
    // 不需要身份校验 直接通过
    next()
  }
})

router.afterEach(to => {
})

export default router
